package com.wjy.game;

import com.wjy.game.service.ServerSocketService;
import com.wjy.game.viewer.ManagerViewer;
import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author wjy
 * @date 2025/5/21 15:54
 * @description 服务器连接
 */
@Getter
@Slf4j
@Component
public class ConnectServer {

    private volatile boolean running = false;

    @Resource
    private ObjectProvider<ServerSocketService> provider;

    @Resource
    private ManagerViewer viewer;

    private transient ServerSocket server;

    public void start(int port) {
        if (server != null && !server.isClosed()) {
            viewer.getMessageBoard().append("服务器已经启动成功\n");
        }
        try {
            server = new ServerSocket(port);
            viewer.getMessageBoard().append("服务器启动成功\n");
            running = true;
            while (running) {
                Socket socket = server.accept();
                ServerSocketService service = provider.getObject();
                service.setSocket(socket);
                service.run();
            }
        } catch (IOException e) {
            log.error("服务器启动发生异常，异常信息：{}", e.getMessage());
            viewer.getMessageBoard().append(String.format("服务器启动发生异常，异常信息：%s\n", e.getMessage()));
        }
    }

    public boolean stop() {
        if (server == null) {
            viewer.getMessageBoard().append("服务器还未启动服务\n");
        } else {
            if (server.isClosed()) {
                viewer.getMessageBoard().append("服务器已经关闭\n");
            } else {
                try {
                    server.close();
                    viewer.getMessageBoard().append("服务器关闭成功\n");
                    return true;
                } catch (IOException e) {
                    log.error("服务器启动关闭异常，异常信息：{}", e.getMessage());
                    viewer.getMessageBoard().append(String.format("服务器关闭发生异常，异常信息：%s\n", e.getMessage()));
                }
            }
        }
        return false;
    }


}
